package com.itheima.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.pojo.Result;
import com.itheima.common.utils.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建文件上传方法
 * 接收文件
 * 文件参数
 *  1.后缀
 *  2.文件字节码数组
 *  3.文件大小
 */
@RestController
@RequestMapping()
public class DfsController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 文件上传
     */
    @PostMapping(value = "/upload")
    public Result upload(MultipartFile multipartFile) throws IOException {
        //后缀
        String extName = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
        //文件字节码数组,数据流
        InputStream is = multipartFile.getInputStream();
        //文件大小
        long size = multipartFile.getSize();
        //文件上传
        StorePath storePath = fastFileStorageClient.uploadFile(is, size, extName, null);
        //得到储存的地址
        String url = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
        //返回存储的地址
        return Result.ok(url);
    }

    /**
     * 文件删除
     */
    @DeleteMapping(value = "/delete")
    public Result delete(String path){
        if (path.startsWith("http://")){
            path = path.replace(fdfsWebServer.getWebServerUrl(),"");
        }
        fastFileStorageClient.deleteFile(path);
        return Result.ok();

    }

    /***
     * 下载
     */
    @GetMapping(value = "/download")
    public void downloadOne(String path) throws IOException {
        byte[] bytes = fastFileStorageClient.downloadFile("group1", path, new DownloadByteArray());
        HttpServletResponse response = RequestContext.getResponse();
        //用 / 分割
        String[] split = path.split("/");
        response.setCharacterEncoding("UTF-8");
        //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
        //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
        // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(split[split.length-1], "UTF-8"));
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + bytes.length);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(bytes);
        outputStream.flush();
    }

    /**
     * 批量下载
     * @param images
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/list/download")
    List<byte[]> download(@RequestParam List<String> images) throws Exception{
        List<byte[]> imageBytes = new ArrayList<>();
        for (String image : images) {
            if (image.startsWith("http://")){
                image = image.replace(fdfsWebServer.getWebServerUrl()+"group1/","");
            }
            byte[] bytes = fastFileStorageClient.downloadFile("group1", image, new DownloadByteArray());
            imageBytes.add(bytes);
        }
        return imageBytes;

    }




}
